<template>
  <div class="map-Wrap">
    <div id="allmap"></div>
    <div id="result">
      详细的地址：
      <div id="result_l"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted } from "vue";
interface Props {
  lng: number;
  lat: number;
}
const props = withDefaults(defineProps<Props>(), {
  lng: 120.658891,
  lat: 31.405307
});
// 初始化地图
function init() {
  let map = new BMapGL.Map("allmap"); // 创建Map实例
  let point = new BMapGL.Point(props.lng, props.lat); // 创建点坐标
  let convertor = new BMapGL.Convertor();
  let pointArr = [];
  pointArr.push(point);
  convertor.translate(pointArr, 1, 5, data => {
    //坐标转换完之后的回调函数
    if (data.status === 0) {
      console.log(data.points[0]);
      let point = data.points[0];
      map.centerAndZoom(point, 18);
      map.enableScrollWheelZoom(); // 启用滚轮放大缩小
      map.setCenter(point);
      let marker = new BMapGL.Marker(point); // 创建标注
      map.addOverlay(marker); // 将标注添加到地图中
      let geoc = new BMapGL.Geocoder();
      geoc.getLocation(point, function (rs) {
        let addComp = rs.addressComponents;
        document.getElementById("result").innerHTML =
          addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;
      });
    }
  });
}
const loadMapScript = () => {
  // 此处在所需页面引入资源就是，不用再public/index.html中引入
  let script = document.createElement("script");
  script.type = "text/javascript";
  script.className = "loadmap"; // 给script一个类名
  script.src = `//api.map.baidu.com/api?type=webgl&v=1.0&ak=${window.staticConfig.baiduAk}&callback=init`;
  window.init = init;

  let loadmap = document.getElementsByClassName("loadmap");
  if (loadmap) {
    // 每次append script之前判断一下，避免重复添加script资源标签
    for (let i = 0; i < loadmap.length; i++) {
      document.body.removeChild(loadmap[i]);
    }
  }
  document.body.appendChild(script);
};
onMounted(() => {
  loadMapScript(); // 加载百度地图资源
});
</script>
<style scoped>
/* 去除水印 */
::v-deep(.BMap_cpyCtrl) {
  display: none;
}
::v-deep(.anchorBL) {
  display: none !important;
}
.map-Wrap {
  width: 100%;
  height: 100%;
}
#allmap {
  /* // 注意给dom宽高，不然地图不出来 */
  width: 90%;
  height: 100%;
  margin: auto;
}
#result {
  margin-left: 5%;
}
</style>
